﻿@{
    var db = Database.Open((string) App.Database);
    var widgets = (IOrderedEnumerable<dynamic>)Page.Widgets;
}

@if (widgets.Any()) {
    foreach(var widget in widgets){
        
        if ((WidgetType)widget.WidgetType == WidgetType.Html && widget.ZoneId == Page.ZoneId) {
            <div class="@widget.CssClass">
                @Html.Raw(widget.Content)
            </div>
        }
        
        if ((WidgetType)widget.WidgetType == WidgetType.Folder && widget.ZoneId == Page.ZoneId) {
            if (Directory.Exists(Server.MapPath(string.Format("~/Widgets/{0}", widget.WidgetName)))) {
                var files = Directory.GetFiles(Server.MapPath(string.Format("~/Widgets/{0}", (string) widget.WidgetName)));
                if (files.Any()) {
                    var file = files.FirstOrDefault(f => Path.GetExtension(f) == ".cshtml");
                    if (file != null) {
                        <div class="@widget.CssClass">
                            @RenderPage(string.Format("~/Widgets/{0}/{1}", widget.WidgetName, Path.GetFileName(file)), new { Args = widget.Args })
                        </div>
                    }
                }
            }
        }
        
        if ((WidgetType)widget.WidgetType == WidgetType.Menu && widget.ZoneId == Page.ZoneId) {
            var commandText = @"SELECT MenuText, Menus.CssClass AS MenuCSS, MenuItems.CssClass AS MenuItemCSS, Url, Target, Orientation, MenuOrder 
                            FROM MenuItems 
                            INNER JOIN Menus ON MenuItems.MenuId = Menus.MenuId 
                            INNER JOIN Pages ON MenuItems.PageId = Pages.PageId
                            INNER JOIN PageContent ON MenuItems.PageId = PageContent.PageId
                            WHERE Menus.MenuName = @0 AND MenuItems.PageId IN 
                            (SELECT PageId FROM PageContent WHERE PageId IN (SELECT PageId FROM PageContent WHERE Published < GetDate())) 
                            GROUP BY MenuText, Menus.CssClass, MenuItems.CssClass, Url, Target, Orientation, MenuOrder 
                            ORDER BY MenuOrder";
            var menu = db.Query(commandText, (string)widget.WidgetName);
            if(menu.Any()){
                <nav class="@menu.First().Orientation.ToLower()" >
                    <ul class="@menu.First().MenuCSS">
                    @foreach(var item in menu){
                        <li @(item.MenuItemCSS != null ? Html.Raw(string.Format("class=\"{0}\"", item.MenuItemCSS)) : null)><a href="~/@item.Url">@item.MenuText</a></li>
                    }
                    </ul>
                </nav>
            }
        }
        
        if ((WidgetType) widget.WidgetType == WidgetType.Form && widget.ZoneId == Page.ZoneId) {
            var commandText = @"SELECT Legend, FormFieldId, FieldName, LabelText, HelpText, DataTypeId, Required, MinLength, MaxLength, CompareTo, 
                                RequiredErrorMessage, MaxLengthErrorMessage, RangeErrorMessage, CompareToErrorMessage,
                                SmtpServer, SmtpPort, SmtpUserName, SmtpPassword, FromAddress, SmtpEnableSsl, Subject, ToAddress,
                                BeforeSendMessage, SendMessage, SendErrorMessage, ShowFormAfterSending
                                FROM FormFields
                                INNER JOIN Forms ON FormFields.FormId = Forms.FormId 
                                WHERE FormName = @0 ORDER BY DisplayOrder";
            var formData = db.Query(commandText, (string) widget.WidgetName);
            if (formData.Any()) {
                var form = formData.First();
                var sent = false;
                var sendErrorMessage = string.Empty;
                if (IsPost && Validation.IsValid()) {
                    try {
                        WebMail.EnableSsl = form.SmtpEnableSsl;
                        WebMail.SmtpServer = form.SmtpServer;
                        WebMail.From = form.FromAddress;
                        WebMail.UserName = form.SmtpUserName;
                        WebMail.Password = form.SmtpPassword;
                        WebMail.SmtpPort = form.SmtpPort != null ? (int) form.SmtpPort : 25;
                    var subject = form.Subject;
                    var body = string.Empty;
                    foreach (string item in Request.Form) {
                        if (item.StartsWith("form-")) {
                            body += item + ": " + Request[item] + "<br />";
                        }
                    }
                    WebMail.Send(
                        to: form.ToAddress,
                        subject: subject,
                        body: body,
                        from: form.FromAddress
                        );
                    sent = true;
                    }
                    catch (Exception ex) {
                        sent = false;
                        sendErrorMessage = form.SendErrorMessage ?? ex.Message;
                    }
                }
                
                <script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
                <script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
                if (!IsPost) {
                    <div>@Html.Raw(form.BeforeSendMessage)</div>
                }
                if (IsPost && Validation.IsValid() && !sent) {
                    <div>@Html.Raw(sendErrorMessage)</div>
                }
                if (sent && !form.ShowFormAfterSending) {
                    <div>@Html.Raw(form.SendMessage)</div>
                }
                else {
                    if (sent) {
                        <div>@Html.Raw(form.SendMessage)</div>
                    }
                    <form id="@((string)widget.WidgetName.Replace(" ", "-").ToLower())" method="post">
                        <fieldset>
                            <legend>@form.Legend</legend>
                            @foreach (var field in formData) {
                                var fieldname = field.FieldName.ToString().ToLower().Replace(" ", "-");
                                if (field.Required) {
                                    Validation.Add(fieldname, Validator.Required(field.RequiredErrorMessage));
                                }
                                if ((FormFieldType)field.DataTypeId == FormFieldType.Numeric) {
                                    Validation.Add(fieldname, Validator.Integer());
                                }
                                if ((FormFieldType)field.DataTypeId == FormFieldType.Email) {
                                    Validation.Add(fieldname, Validator.Regex(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$", "Must be a valid email address"));
                                }
                                if ((FormFieldType)field.DataTypeId == FormFieldType.Url) {
                                    Validation.Add(fieldname, Validator.Url());
                                }
                                if (field.CompareTo != null) {
                                    var compareField = formData.FirstOrDefault(f => f.FormFieldId.Equals(field.CompareTo)).FieldName;
                                    if (compareField != null) {
                                        Validation.Add(fieldname, Validator.EqualsTo(compareField.ToString().ToLower().Replace(" ", "-"), field.CompareToErrorMessage));
                                    }
                                }
                                if (field.MinLength != null && field.MaxLength != null) {
                                    Validation.Add(fieldname, Validator.Range((double)field.MinLength, (double)field.MaxLength, field.RangeErrorMessage));
                                }
                                else {
                                    if (field.MaxLength != null) {
                                        Validation.Add(fieldname, Validator.StringLength(0, field.MaxLength, field.MaxLengthErrorMessage));
                                    }
                                    if(field.MinLength != null){
                                        Validation.Add(fieldname, Validator.StringLength(field.MinLength, Int32.MaxValue, field.MinLengthErrorMessage));
                                    }
                                }

                                if ((FormFieldType)field.DataTypeId != FormFieldType.LongText && (FormFieldType)field.DataTypeId != FormFieldType.Submit) {
                                    @ControlGroup.TextBox(field.LabelText, fieldname, field.HelpText)
                                }
                                if ((FormFieldType)field.DataTypeId == FormFieldType.LongText) {
                                    @ControlGroup.TextArea(field.LabelText, fieldname, field.HelpText)
                                }
                                if ((FormFieldType)field.DataTypeId == FormFieldType.Submit) {
                                    @ControlGroup.Button(text: field.LabelText)
                                }
                            }
                        </fieldset>
                    </form>
                }
            }
        }
    }
}